package p2pscrabble;

import java.util.Random;

public class TilesBag {

	// composition of each letter: 9a, 2b, 2c, 4d, ....., 1z, 2 blanks
	private char letters[] = { 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
			'A', 'B', 'B', 'C', 'C', 'D', 'D', 'D', 'D', 'E', 'E', 'E', 'E',
			'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'F', 'F', 'G', 'G', 'G',
			'H', 'H', 'I', 'I', 'I', 'I', 'I', 'I', 'I', 'I', 'I', 'J', 'K',
			'L', 'L', 'L', 'L', 'M', 'M', 'N', 'N', 'N', 'N', 'N', 'N', 'O',
			'O', 'O', 'O', 'O', 'O', 'O', 'O', 'P', 'P', 'Q', 'R', 'R', 'R',
			'R', 'R', 'R', 'S', 'S', 'S', 'S', 'T', 'T', 'T', 'T', 'T', 'T',
			'U', 'U', 'U', 'U', 'V', 'V', 'W', 'W', 'X', 'Y', 'Y', 'Z', ' ',
			' ' };

	private static int letterScore[] = { 1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3,
			1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10, 0 };

	private int counter;
	private Random rand = new Random();
	
	public TilesBag() {
		counter = -1;
	}
	
	public TilesBag(char[] letters, int counter) {
		this.letters = letters;
		this.counter = counter;
	}

	public char getLetterFromBag() {
		if (counter >= 99)
			return '-';
		counter ++;
		return letters[counter];
	}
	
	public int getLetterScore(char l) {
		int i;
		if (l <= 90)
			i = (int) l - 65;
		else
			i = 26;

		return letterScore[i];
	}

	public void shuffleLetters() {
		int last = letters.length - 1 - counter;
		int nextRand;

		while (last > 0) {
			nextRand = rand.nextInt(last);
			swap(nextRand + counter + 1, last + counter);
			last--;
		}
	}

	private void swap(int j, int k) {
		char temp = letters[k];
		letters[k] = letters[j];
		letters[j] = temp;
	}
	
	public char swapAction(char letter, int i) {
		char swapLetter = letters[counter + i + 1];
		
		if (letter > 90)
			letter = ' ';
		
		letters[counter + i + 1] = letter;
		return swapLetter;
	}
	
	public char[] getAllLetters() {
		return letters;
	}
	
	public char[] getAllLetters(int i, int j) {
		char[] let = new char [j-i];
		for (int b=0; b<j-i; b++) {
			let[b] = letters[i+b]; 
		}
		return let;
	}
	
	public void setLetter(char[] letters) {
		this.letters = letters;
	}
	
	public int getCounter() {
		return counter;
	}
	
	public void setCounter(int c) {
		counter = c;
	}
}
